<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class PermissionNode extends Model
{
    use HasFactory;

    protected $fillable = [
        'code',
        'name',
        'type',
        'resource',
        'description',
        'status',
    ];

    /**
     * 获取关联的功能
     */
    public function functions(): BelongsToMany
    {
        return $this->belongsToMany(FunctionModel::class, 'function_permissions')
            ->withTimestamps();
    }

    /**
     * 检查权限节点是否启用
     */
    public function isActive(): bool
    {
        return $this->status === 'active';
    }

    /**
     * 获取权限类型标签
     */
    public function getTypeLabelAttribute(): string
    {
        return match ($this->type) {
            'page' => '页面权限',
            'api' => 'API权限',
            'field' => '字段权限',
            default => $this->type,
        };
    }

    /**
     * 获取状态标签
     */
    public function getStatusLabelAttribute(): string
    {
        return match ($this->status) {
            'active' => '启用',
            'inactive' => '禁用',
            default => $this->status,
        };
    }

    /**
     * 作用域：活跃权限节点
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * 作用域：按类型筛选
     */
    public function scopeByType($query, string $type)
    {
        return $query->where('type', $type);
    }

    /**
     * 作用域：API权限
     */
    public function scopeApi($query)
    {
        return $query->where('type', 'api');
    }

    /**
     * 作用域：页面权限
     */
    public function scopePage($query)
    {
        return $query->where('type', 'page');
    }

    /**
     * 作用域：字段权限
     */
    public function scopeField($query)
    {
        return $query->where('type', 'field');
    }
}
